package com.zhiyuan.audio;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.widget.Toast;
import com.zhiyuan.audio.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.Manifest;
import com.zhiyuan.audio.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;

    private static final String TAG = "UVAAudioManager";
    private static final int PERMISSION_REQUEST_CODE = 1001;


    private AudioManager audioManager;
    private Button btnDiscover, btnStartRecord, btnStopRecord, btnPlay, btnStop;
    private Button btnStartPcmStream, btnStopPcmStream, btnStartRecordWithPcm, btnStopRecordWithPcm;

    private TextView tvStatus, tvDeviceInfo;
    private TextView tvPcmInfo, tvPcmDataStats;

    private RecyclerView rvDevices;
    private AudioDeviceAdapter deviceAdapter;

    private long totalPcmBytesReceived = 0;
    private int pcmDataPacketCount = 0;
    private long pcmStreamStartTime = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        initAudioManager();
        requestPermissions();
        setupClickListeners();

        setupPcmDataListener();
    }


    private void initView(){
        btnDiscover = binding.btnDiscover;
        btnStartRecord = binding.btnStartRecord;
        btnStopRecord = binding.btnStopRecord;
        btnPlay = binding.btnPlay;
        btnStop = binding.btnStop;

        try {
            btnStartPcmStream = binding.btnStartPcmStream;
            btnStopPcmStream = binding.btnStopPcmStream;
            btnStartRecordWithPcm = binding.btnStartRecordWithPcm;
            btnStopRecordWithPcm = binding.btnStopRecordWithPcm;

            // 初始状态设置
            btnStopPcmStream.setEnabled(false);
            btnStopRecordWithPcm.setEnabled(false);
        } catch (Exception e) {
            // 如果布局文件中没有这些按钮，设为null
            Log.w(TAG, "PCM相关按钮未在布局中找到，可能需要更新布局文件");
            btnStartPcmStream = null;
            btnStopPcmStream = null;
            btnStartRecordWithPcm = null;
            btnStopRecordWithPcm = null;
        }


        tvStatus = binding.tvStatus;
        tvDeviceInfo = binding.tvDeviceInfo;
        try {
            tvPcmInfo = binding.tvPcmInfo;
            tvPcmDataStats = binding.tvPcmDataStats;
        } catch (Exception e) {
            Log.w(TAG, "PCM信息显示控件未在布局中找到");
            tvPcmInfo = null;
            tvPcmDataStats = null;
        }

        rvDevices = binding.rvDevices;

        deviceAdapter = new AudioDeviceAdapter();
        rvDevices.setLayoutManager(new LinearLayoutManager(this));
        rvDevices.setAdapter(deviceAdapter);
    }

    private void  initAudioManager() {
        audioManager = new com.zhiyuan.audio.AudioManager(this, new com.zhiyuan.audio.AudioManager.AudioCallback() {
            @Override
            public void onDeviceFound(AudioDevice device) {
                runOnUiThread(() -> {
                    deviceAdapter.addDevice(device);
                    tvStatus.setText("发现设备: " + device.getName());
                });
            }

            @Override
            public void onRecordingStarted() {
                runOnUiThread(() -> {
                    tvStatus.setText("录音已开始");
                    btnStartRecord.setEnabled(false);
                    btnStopRecord.setEnabled(true);

                    if (btnStartRecordWithPcm != null) btnStartRecordWithPcm.setEnabled(false);
                    if (btnStopRecordWithPcm != null) btnStopRecordWithPcm.setEnabled(true);
                });
            }

            @Override
            public void onRecordingStopped() {
                runOnUiThread(() -> {
                    tvStatus.setText("录音已停止");
                    btnStartRecord.setEnabled(true);
                    btnStopRecord.setEnabled(false);

                    if (btnStartRecordWithPcm != null) btnStartRecordWithPcm.setEnabled(true);
                    if (btnStopRecordWithPcm != null) btnStopRecordWithPcm.setEnabled(false);
                });
            }

            @Override
            public void onPlaybackStarted() {
                runOnUiThread(() -> {
                    tvStatus.setText("播放已开始");
                    btnPlay.setEnabled(false);
                    btnStop.setEnabled(true);
                });
            }

            @Override
            public void onPlaybackStopped() {
                runOnUiThread(() -> {
                    tvStatus.setText("播放已停止");
                    btnPlay.setEnabled(true);
                    btnStop.setEnabled(false);
                });
            }

            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    tvStatus.setText("错误: " + error);
                    resetButtons();
                });
            }

            @Override
            public void onMuteStateChanged(AudioDevice device, boolean muted) {
                runOnUiThread(() -> {
                    tvStatus.setText(device.getName() + (muted ? " 已静音" : " 已取消静音"));
                    deviceAdapter.updateDevice(device);
                });
            }

            @Override
            public void onVolumeChanged(AudioDevice device, float volume) {
                runOnUiThread(() -> {
                    tvStatus.setText(String.format("%s 音量: %.0f%%", device.getName(), volume * 100));
                    deviceAdapter.updateDevice(device);
                });
            }

            @Override
            public void onMuteUnsupported(AudioDevice device, String reason) {
                runOnUiThread(() -> {
                    tvStatus.setText("静音不支持: " + reason);
                });
            }
        });
    }

    private void setupPcmDataListener() {
        AudioManager.PcmDataListener pcmListener = new AudioManager.PcmDataListener() {
            @Override
            public void onPcmDataReceived(byte[] pcmData, int bytesRead, int sampleRate, int channelCount, int audioFormat) {
                // 统计数据
                totalPcmBytesReceived += bytesRead;
                pcmDataPacketCount++;

                // 每100个数据包更新一次UI（避免过于频繁的UI更新）
                if (pcmDataPacketCount % 100 == 0) {
                    runOnUiThread(() -> updatePcmStats());
                }

                // 这里可以添加你的PCM数据处理逻辑
                // 例如：语音识别、音频分析、实时传输等
                Log.e("lucas","1111.....");
                processPcmData(pcmData, bytesRead, sampleRate, channelCount, audioFormat);
            }

            @Override
            public void onPcmStreamStarted() {
                pcmStreamStartTime = System.currentTimeMillis();
                totalPcmBytesReceived = 0;
                pcmDataPacketCount = 0;

                runOnUiThread(() -> {
                    tvStatus.setText("PCM数据流已开始");
                    if (btnStartPcmStream != null) btnStartPcmStream.setEnabled(false);
                    if (btnStopPcmStream != null) btnStopPcmStream.setEnabled(true);

                    if (tvPcmInfo != null) {
                        AudioManager.AudioParams params = audioManager.getCurrentAudioParams();
                        tvPcmInfo.setText(String.format("PCM参数: %s", params.toString()));
                    }
                });
            }

            @Override
            public void onPcmStreamStopped() {
                runOnUiThread(() -> {
                    tvStatus.setText("PCM数据流已停止");
                    if (btnStartPcmStream != null) btnStartPcmStream.setEnabled(true);
                    if (btnStopPcmStream != null) btnStopPcmStream.setEnabled(false);

                    // 显示最终统计信息
                    updatePcmStats();
                });
            }

            @Override
            public void onPcmStreamError(String error) {
                runOnUiThread(() -> {
                    tvStatus.setText("PCM数据流错误: " + error);
                    Toast.makeText(MainActivity.this, "PCM错误: " + error, Toast.LENGTH_SHORT).show();

                    // 重置按钮状态
                    if (btnStartPcmStream != null) btnStartPcmStream.setEnabled(true);
                    if (btnStopPcmStream != null) btnStopPcmStream.setEnabled(false);
                });
            }
        };

        // 添加PCM数据监听器
        audioManager.addPcmDataListener(pcmListener);
    }

    // 新增：处理PCM数据的示例方法
    private void processPcmData(byte[] pcmData, int bytesRead, int sampleRate, int channelCount, int audioFormat) {
        // 这里是PCM数据处理的示例代码
        // 你可以根据需求实现以下功能：

        // 1. 音频分析（音量检测）
        float volume = calculateVolume(pcmData, bytesRead, audioFormat);

        // 2. 语音活动检测（VAD）
        boolean speechDetected = detectSpeech(volume);

        // 3. 实时传输到服务器
        // sendPcmDataToServer(pcmData, bytesRead);

        // 4. 保存到缓冲区进行批处理
        // addToPcmBuffer(pcmData, bytesRead);

        // 5. 格式转换
        // float[] floatData = convertToFloat(pcmData, bytesRead, audioFormat);

        // 记录日志（仅在调试时启用）
        if (pcmDataPacketCount % 1000 == 0) {
            Log.d(TAG, String.format("PCM数据 - 包序号: %d, 字节数: %d, 音量: %.2f, 语音检测: %s",
                    pcmDataPacketCount, bytesRead, volume, speechDetected ? "是" : "否"));
        }
    }

    // 新增：计算音频音量（RMS）
    private float calculateVolume(byte[] pcmData, int bytesRead, int audioFormat) {
        if (audioFormat == android.media.AudioFormat.ENCODING_PCM_16BIT) {
            // 16位PCM数据处理
            long sum = 0;
            int sampleCount = bytesRead / 2; // 16位 = 2字节

            for (int i = 0; i < bytesRead - 1; i += 2) {
                // 将字节转换为16位整数（小端序）
                short sample = (short) ((pcmData[i + 1] << 8) | (pcmData[i] & 0xFF));
                sum += sample * sample;
            }

            if (sampleCount > 0) {
                double rms = Math.sqrt((double) sum / sampleCount);
                return (float) (rms / 32768.0); // 归一化到0-1范围
            }
        }
        return 0.0f;
    }

    // 新增：简单的语音活动检测
    private boolean detectSpeech(float volume) {
        // 简单的阈值检测，实际应用中可以使用更复杂的算法
        final float SPEECH_THRESHOLD = 0.01f; // 可以根据环境调整
        return volume > SPEECH_THRESHOLD;
    }

    // 新增：更新PCM数据统计信息
    private void updatePcmStats() {
        if (tvPcmDataStats != null) {
            long elapsedTime = System.currentTimeMillis() - pcmStreamStartTime;
            double dataRateKBps = (totalPcmBytesReceived / 1024.0) / (elapsedTime / 1000.0);

            String statsText = String.format(
                    "数据包: %d\n总字节: %d\n运行时间: %.1fs\n数据速率: %.1f KB/s",
                    pcmDataPacketCount,
                    totalPcmBytesReceived,
                    elapsedTime / 1000.0,
                    dataRateKBps
            );
            tvPcmDataStats.setText(statsText);
        }
    }

    private void resetButtons() {
        btnStartRecord.setEnabled(true);
        btnStopRecord.setEnabled(false);
        btnPlay.setEnabled(true);
        btnStop.setEnabled(false);

        // PCM按钮重置
        if (btnStartPcmStream != null) btnStartPcmStream.setEnabled(true);
        if (btnStopPcmStream != null) btnStopPcmStream.setEnabled(false);
        if (btnStartRecordWithPcm != null) btnStartRecordWithPcm.setEnabled(true);
        if (btnStopRecordWithPcm != null) btnStopRecordWithPcm.setEnabled(false);
    }

    private void requestPermissions() {
        String[] permissions = {
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };

        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    }

    private void setupClickListeners() {
        btnDiscover.setOnClickListener(v -> {
            deviceAdapter.clearDevices();
            audioManager.discoverDevices();
        });

        btnStartRecord.setOnClickListener(v -> audioManager.startRecording());
        btnStopRecord.setOnClickListener(v -> audioManager.stopRecording());
        btnPlay.setOnClickListener(v -> audioManager.startPlayback());
        btnStop.setOnClickListener(v -> audioManager.stopPlayback());


        // PCM相关按钮监听器 - 新增
        if (btnStartPcmStream != null) {
            btnStartPcmStream.setOnClickListener(v -> {
                if (audioManager.getSelectedDevice() == null) {
                    Toast.makeText(this, "请先选择音频设备", Toast.LENGTH_SHORT).show();
                    return;
                }
                audioManager.startPcmStreaming();
            });
        }

        if (btnStopPcmStream != null) {
            btnStopPcmStream.setOnClickListener(v -> audioManager.stopPcmStreaming());
        }

        if (btnStartRecordWithPcm != null) {
            btnStartRecordWithPcm.setOnClickListener(v -> {
                if (audioManager.getSelectedDevice() == null) {
                    Toast.makeText(this, "请先选择音频设备", Toast.LENGTH_SHORT).show();
                    return;
                }
                audioManager.startRecordingWithPcmStream();
            });
        }

        if (btnStopRecordWithPcm != null) {
            btnStopRecordWithPcm.setOnClickListener(v -> audioManager.stopRecordingWithPcmStream());
        }


        deviceAdapter.setOnDeviceClickListener(device -> {
            audioManager.selectDevice(device);
            tvDeviceInfo.setText("已选择: " + device.getName() +
                    "\n类型: " + device.getType().getDisplayName() +
                    "\n状态: " + (device.isAvailable() ? "可用" : "不可用"));
        });

        deviceAdapter.setOnDeviceControlListener(new AudioDeviceAdapter.OnDeviceControlListener() {
            @Override
            public void onMuteToggle(AudioDevice device) {
                audioManager.toggleDeviceMute(device);
            }

            @Override
            public void onVolumeChange(AudioDevice device, float volume) {
                audioManager.setDeviceVolume(device, volume);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (audioManager != null) {
            audioManager.release();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 在应用暂停时停止PCM数据流以节省资源
        if (audioManager != null && audioManager.isPcmStreaming()) {
            audioManager.stopPcmStreaming();
        }
    }

    public void startSpeechRecognition() {
        // 启动语音识别时可以调用此方法
        if (audioManager != null) {
            if (!audioManager.isPcmStreaming()) {
                audioManager.startPcmStreaming();
            }
        }
    }

    public void stopSpeechRecognition() {
        // 停止语音识别时调用
        if (audioManager != null && audioManager.isPcmStreaming()) {
            audioManager.stopPcmStreaming();
        }
    }

    // 新增：获取实时PCM数据的回调接口（供其他组件使用）
    public interface RealTimePcmCallback {
        void onPcmData(byte[] data, int length, AudioManager.AudioParams params);
    }

    private RealTimePcmCallback realTimePcmCallback;

    public void setRealTimePcmCallback(RealTimePcmCallback callback) {
        this.realTimePcmCallback = callback;
    }

    // 在processPcmData方法中调用回调
    private void notifyRealTimePcmCallback(byte[] pcmData, int bytesRead) {
        if (realTimePcmCallback != null) {
            AudioManager.AudioParams params = audioManager.getCurrentAudioParams();
            realTimePcmCallback.onPcmData(pcmData, bytesRead, params);
        }
    }


}